﻿using System;
using System.Linq;
using Landpy.CruiseControlNet.FacadeInterface.ConfigurationModule;
using Landpy.CruiseControlNet.FacadeInterface.RepositoryModule;
using Landpy.CruiseControlNet.Infrastructure.Aop.WrapAttribute;

namespace Landpy.CruiseControlNet.DomainLayer.RepositoryModule
{
    public class SecurityUserRepository : ISecurityUserRepository
    {
        private IProjectRepository ProjectRepository { get; set; }
        private IPermissionRepository PermissionRepository { get; set; }

        public SecurityUserRepository()
        {
            this.ProjectRepository = new ProjectRepository();
            this.PermissionRepository = new PermissionRepository();
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public SecurityUser GetInternalSecurityUserById(InternalSecurity internalSecurity, Guid id)
        {
            return (from SecurityUser securityUser in internalSecurity.Users
                    where securityUser.Id == id
                    select securityUser).FirstOrDefault();
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public SecurityUser GetInternalRolePermissonSecurityUserById(CruiseControl cruiseControl, Guid permissionId, Guid id)
        {
            SecurityUser securityUser = null;
            var queryPermission = this.PermissionRepository.GetInternalRolePermissionById(
                cruiseControl.InternalSecurity, permissionId);
            if (queryPermission != null)
            {
                securityUser = (from UserName userName in queryPermission.UserNames
                                where userName.Id == id
                                select userName).FirstOrDefault();
            }
            return securityUser;
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public SecurityUser GetProjectRolePermissonSecurityUserById(CruiseControl cruiseControl, Guid projectId, Guid permissionId, Guid id)
        {
            SecurityUser securityUser = null;
            var queryPermission = this.PermissionRepository.GetProjectRolePermissionById(cruiseControl, projectId, permissionId);
            if (queryPermission != null)
            {
                securityUser = (from UserName userName in queryPermission.UserNames
                                where userName.Id == id
                                select userName).FirstOrDefault();
            }
            return securityUser;
        }
    }
}
